import {iRuleRecord} from "./RuleList";
import {defer} from "@peryl/utils/defer";
import {$dialog, Form, FormInput} from "plain-design";
import {designComponent, PropType, reactive, useRefs} from "@peryl/react-compose";
import {deepcopy} from "@peryl/utils/deepcopy";

export const RuleDetail = (() => {

  const openEditor = (initialRuleRecord?: Partial<iRuleRecord>, type: 'create' | 'edit' = 'create')
    : Promise<Partial<iRuleRecord>> => {
    if (!initialRuleRecord) {initialRuleRecord = {};}
    const dfd = defer<Partial<iRuleRecord>>();

    const { refs, onRef } = useRefs({ ruleForm: RuleForm }, { reactive: false });

    $dialog({
      position: 'right',
      title: type === 'edit' ? '编辑规则' : '新建规则',
      confirmButton: true,
      cancelButton: true,
      handleConfirm: async () => {
        await refs.ruleForm!.refs.form!.validate();
        dfd.resolve(refs.ruleForm!.state.formData);
      },
      handleCancel: () => dfd.reject('cancel'),
      render: () => (<RuleForm ref={onRef.ruleForm} initialRuleRecord={initialRuleRecord}/>)
    });

    return dfd.promise;
  };

  return { openEditor };
})();

const RuleForm = designComponent({
  props: {
    initialRuleRecord: { type: Object as PropType<Partial<iRuleRecord>> }
  },
  setup({ props }) {

    const { refs, onRef } = useRefs({ form: Form });

    const state = reactive({
      formData: deepcopy(props.initialRuleRecord) || {}
    });

    // if (!state.formData.name) {state.formData.name = '订单满减促销';}
    // if (!state.formData.comments) {state.formData.comments = '订单金额满100的话，就赠送余额';}

    return {
      refer: { refs, state },
      render: () => (
        <Form ref={onRef.form} validateMessagePosition="bottom-right">
          <FormInput label="规则名称" v-model={state.formData.name} required/>
          <FormInput label="备注信息" textarea v-model={state.formData.comments}/>
        </Form>
      )
    };
  },
});
